package com.itcast.cn.conversation.controller;

import com.itcast.cn.conversation.pojo.User;
import com.itcast.cn.conversation.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

/**
 * @author hyatt
 * @version 1.0
 */
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String remember = request.getParameter("remember");

        // 如果用户名密码正确, 添加到cookie中, 下载不用再次输入
        User user = userService.select(username, password);
        if (user != null) {
            if ("1".equals(remember)) {
                Cookie c_username = new Cookie("username", username);
                Cookie c_password = new Cookie("password", password);
                c_username.setMaxAge(60 * 60 * 24 * 7);
                c_password.setMaxAge(60 * 60 * 24 * 7);
                // 添加cookie
                response.addCookie(c_username);
                response.addCookie(c_password);
            }
            // 将user添加到session中
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            // 跳转到selectAllServlet
            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath + "/selectAll");

        } else {
            // 登陆失败
            request.setAttribute("errorMsg", "用户名或者密码不正确");
            // 跳转到login.jsp
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
